package com.lanou.dllo.findfood.database;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.lanou.dllo.findfood.entity.FindTopResult;
import com.lanou.dllo.findfood.util.Constant;


import java.util.ArrayList;
import java.util.List;

/**
 * Created by dllo on 15/10/31.
 */
public class FindViewPageDataUtil {
    private SQLiteDatabase database;

    public FindViewPageDataUtil(Context context) {
        init(context);
    }

    private void init(Context context) {
         //factory 游标, version
        //构建数据库帮助类用于数据库对象的获取
        //参数二表示数据库名
        MySQLiteOpenHelper helper = new MySQLiteOpenHelper(context, Constant.DATABASE_NAME, null, 1);
        database = helper.getWritableDatabase();
    }

    //以键值对的形式保存
    public void saveAll(List<FindTopResult> dealsList) {
        for (FindTopResult homeTopDeals : dealsList) {
            ContentValues values = new ContentValues();
            values.put(Constant.COLUMN_FIND_TOP_VIEWPAGE_FOOD_ID, homeTopDeals.getId());
            values.put(Constant.COLUMN_FIND_TOP_VIEWPAGE_IMGURL, homeTopDeals.getImg());
            values.put(Constant.COLUMN_FIND_TOP_VIEWPAGE_TITLE, homeTopDeals.getTitle());
            database.insert(Constant.TABLE_NAME_FIND_TOP_VIEWPAGE, null, values);


        }
    }


    public List<FindTopResult> queryAll() {

        Cursor cursor = database.query(Constant.TABLE_NAME_FIND_TOP_VIEWPAGE, null,
                null, null, null, null, null);
        if (cursor != null) {
            List<FindTopResult> dealses = new ArrayList<FindTopResult>();
            while (cursor.moveToNext()) {
                String image = cursor.getString(cursor.getColumnIndex(Constant.COLUMN_FIND_TOP_VIEWPAGE_IMGURL));
                int id = cursor.getInt(cursor.getColumnIndex(Constant.COLUMN_FIND_TOP_VIEWPAGE_FOOD_ID));
                String title = cursor.getString(cursor.getColumnIndex(Constant.COLUMN_FIND_TOP_VIEWPAGE_TITLE));
                FindTopResult deals = new FindTopResult();
                deals.setId(id);
                deals.setTitle(title);
                deals.setImg(image);
                dealses.add(deals);
            }
            cursor.close();
            return dealses;
        }


        return null;
    }
    public void deleData() {
        database.delete(Constant.TABLE_NAME_FIND_TOP_VIEWPAGE, null, null);
    }

}
